package javango.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.text.StrBuilder;

public class HttpResponseRedirect implements javango.http.HttpResponse {

	protected String url;
	
	// TODO Should the map be <String, String[]>??
	protected Map<String, String> parameters; 
	
	public HttpResponseRedirect(String url, Map<String, String> parameters){
		this.parameters = parameters;		
		this.url = url;
	}
	
	public HttpResponseRedirect(String url) {
		this.url = url;
	}

	public HttpResponseRedirect(String url, Object... args) {
		this.url = String.format(url, args);
	}
	public void render(HttpServletRequest req, HttpServletResponse resp) throws HttpException {
		try {
			String finalUrl = url;
			if(parameters != null && !parameters.isEmpty()){
				// TODO Should this instead check for url.contains("?")?? 
				finalUrl += ('/' == url.charAt(finalUrl.length() - 1)) ? "?" : "";
				
				StrBuilder query = new StrBuilder();

				for(Entry<String, String> param : parameters.entrySet()){
					query.appendSeparator('&');
					query.append(encode(param.getKey())).append('=').append(encode(param.getValue()));
				}
				
				finalUrl += query.toString();
			}

			resp.sendRedirect(finalUrl);
		} catch (IOException e) {
			throw new HttpException(e);
		}
	}
	
	public String encode(String toEncode) {
		try {
			return URLEncoder.encode(toEncode, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Encoding error, UTF-8 is not available", e);
		}
	}

	public String getUrl() {
		return url;
	}

	public Map<String, Object> getContext() {
		return null;
	}
	
	
	
}
